<script setup lang="ts">
import type { Question, QuestionOption, Answer, AnswerType } from "./examination"
import { isValidJSON } from '#/utils/isValidJSON'
defineOptions({ name: 'QuestionDetail' });

defineProps({
  examData: {
    type: Object as any,
    default: () => { }
  },
  createIdx: {
    type: Function,
    default: () => { }
  },
  scoreUpdate: {
    type: Function,
    default: () => { }
  }
});

// 工具函数：检查答案是否为空
const isEmptyAnswer = (userAnswer: string, type: string): boolean => {
  const emptyPatterns = {
    trueFalse: '{}',
    radio: '[]',
    checkbox: '[]'
  }
  return userAnswer === emptyPatterns[type as keyof typeof emptyPatterns]
}
// 工具函数：安全解析JSON
const safeParseJSON = <T>(jsonString: string | null | undefined): T | null => {
  if (!jsonString) {
    return null
  }
  if (!isValidJSON(jsonString)) {
    return jsonString as T
  }
  try {
    return JSON.parse(jsonString)
  } catch {
    return null
  }
}

// 工具函数：检查选项是否匹配答案
const isOptionInAnswer = (opt: QuestionOption, answer: AnswerType): boolean => {
  if (!answer) return false

  // 处理对象数组格式
  if (Array.isArray(answer) && answer.length > 0 && typeof answer[0] === 'object' && 'id' in answer[0]) {
    return (answer as Answer[]).some((a: Answer) => a.id === opt?.id)
  }
  
  // 处理字符串数组格式
  if (Array.isArray(answer) && answer.length > 0 && typeof answer[0] === 'string') {
    return (answer as string[]).includes(opt?.content || opt?.name || '')
  }
  
  // 处理单个对象格式
  if (typeof answer === 'object' && answer && 'id' in answer) {
    return (answer as Answer).id === opt?.id
  }
  
  // 处理普通字符串格式
  if (typeof answer === 'string') {
    return answer === opt?.content || answer === opt?.name
  }
  
  return false
}

// 计算题型总分
const getTypeScoreTotal = (list: Question[]) => {
  return list.reduce((sum: number, question: Question) => sum + (Number(question.score) || 0), 0)
}

// 获取选项列表
const getOpts = (data: string): QuestionOption[] => {
  return safeParseJSON<QuestionOption[]>(data) || []
}
const getOptContent = (question: Question, opt: QuestionOption) => {
  const contentMap = {
    radio: () => `${opt.name}、${opt.content}`,
    checkbox: () => `${opt.name}、${opt.content}`,
    fillBlank: () => opt.name || '',
    trueFalse: () => opt.name || '',
    default: () => opt.content || opt.name || ''
  }
  
  return contentMap[question.type as keyof typeof contentMap]?.() || contentMap.default()
}
const getOptStyle = (question: Question, opt: QuestionOption) => {
  // 检查答案是否为空
  if (isEmptyAnswer(question.userAnswer, question.type)) {
    return ''
  }

  const answers = safeParseJSON<AnswerType>(question.answers)
  const userAnswer = safeParseJSON<AnswerType>(question.userAnswer)

  if (userAnswer === null) {
    return ''
  }

  const isReferAns = isOptionInAnswer(opt, answers)
  const isUserAns = isOptionInAnswer(opt, userAnswer)

  // 样式逻辑
  if (isUserAns && isReferAns) {
    return 'bg-[#30a46c80]' // 正确答案
  } else if (isUserAns && !isReferAns) {
    return 'bg-[#e5484d80]' // 错误答案
  }

  return ''
}

const getUserAnswers = (question: Question) => {
  const options = safeParseJSON<AnswerType>(question.options)
  const userAnswer = safeParseJSON<AnswerType>(question.userAnswer)

  // 处理空答案情况
  if (isEmptyAnswer(question.userAnswer, question.type) || userAnswer === null) {
    return '--'
  }

  // 处理对象数组格式
  if (Array.isArray(userAnswer) && userAnswer.length > 0 && typeof userAnswer[0] === 'object' && 'id' in userAnswer[0]) {
    const userIds = (userAnswer as Answer[]).map(u => u.id)
    const names = Array.isArray(options) && options.length > 0 && typeof options[0] === 'object' && 'id' in options[0]
      ? (options as Answer[])
        .filter(a => userIds.includes(a.id))
        .map(a => a.name)
        .filter(Boolean)
      : []
    return names.join('、') || '--'
  }

  // 处理单个对象格式 "{\"id\":\"726004518123663362\"}"
  if (userAnswer && typeof userAnswer === 'object' && 'id' in userAnswer) {
    return Array.isArray(options) && options.length > 0 && typeof options[0] === 'object' && 'id' in options[0]
      ? (options as Answer[]).find(opt => opt.id === userAnswer.id)?.name ?? '--'
      : '--'
  }

  // 处理空对象格式 "{}"
  if (userAnswer && typeof userAnswer === 'object' && JSON.stringify(userAnswer) === '{}') {
    return '--'
  }

  // 处理字符串数组格式 "[\"填空1\",\"填空2\"]"
  if (Array.isArray(userAnswer) && userAnswer.length > 0 && typeof userAnswer[0] === 'string') {
    return userAnswer.map(a => a || '--').join('、')
  }

  // 处理空数组格式  "[]"
  if (Array.isArray(userAnswer) && userAnswer.length === 0) {
    return '--'
  }

  // 处理普通字符串格式  "**"
  if (typeof userAnswer === 'string') {
    return userAnswer || '--'
  }

  return '--'
}

const getAnswers = (question: Question) => {
  const answerHandlers = {
    essay: (answers: string) => answers || '--',
    
    fillBlank: (answers: string) => {
      const parsed = safeParseJSON<string[]>(answers)
      return parsed ? parsed.filter(Boolean).join('、') || '--' : answers || '--'
    },
    
    trueFalse: (answers: string) => {
      const parsed = safeParseJSON<Answer | string>(answers)
      if (typeof parsed === 'object' && parsed && 'name' in parsed) {
        return parsed.name || '--'
      }
      return parsed || answers || '--'
    },
    
    default: (answers: string) => {
      const parsed = safeParseJSON<Answer[]>(answers)
      if (Array.isArray(parsed) && parsed.length > 0 && typeof parsed[0] === 'object' && 'name' in parsed[0]) {
        return parsed
          .map((a: Answer) => a.name || a.id)
          .filter(Boolean)
          .join('、') || '--'
      }
      return answers || '--'
    }
  }

  const handler = answerHandlers[question.type as keyof typeof answerHandlers] || answerHandlers.default
  return handler(question.answers)
}

</script>
<template>
  <section>
    <div class="pb-[10px]" v-for="(item, index) in examData.qtyList" :key="index">
      <div class="title mb-[16px] leading-[22px]">
        <span class="text-[16px] mr-[12px] font-[500]">{{ `${createIdx(index)}、${item.name}` }}</span>
        <span class="text-[12px]">{{
          `（${$t('exam.computedTotalTxt')}${item.questions.length}${$t('exam.questionsComputedTxt')}${getTypeScoreTotal(item.questions)}${$t('exam.gradeTxt')}）`
        }}</span>
      </div>
      <div class="q-list border-b border-color:#DCDFE6 pb-[16px] pl-[30px] mb-[15px] last-of-type:mb-[0px]"
        v-for="(q, idx) in item?.questions" :key="idx" :id="`question-${q.id}`">
        <div class="flex flex-wrap q-title text-[14px] leading-[20px] mb-[12px]">
          <div class="q-title-content">
            <span>{{ `${idx + 1}、${q.stem}` }}</span>
            <span class="ml-[5px]">{{ `（${q.score}${$t('exam.gradeTxt')}）` }}</span>
          </div>
        </div>
        <div class="q-options text-[12px] pl-[20px] mb-[8px] last-of-type:mb-[12px] leading-[24px] "
          v-for="(opt, optIdx) in getOpts(q?.options) || []" :key="optIdx">
          <span class="q-options-item text-[#191919] pl-[5px] pt-[3px] pr-[5px] pb-[3px] rounded-[4px]"
            :class="getOptStyle(q, opt)">{{ getOptContent(q, opt) }}</span>
        </div>
        <div class="answer text-[#595959] border border-color:#DCDFE6 rounded-sm p-[12px] text-[12px] leading-[20px]">
          <div class="user-answer mb-[6px]">{{ $t('exam.userAnswerTxt') }} <span class="text-[#191919] ml-[5px]">{{ getUserAnswers(q) }}</span></div>
          <div class="reference-answer mb-[6px]">{{ $t('exam.perforAnswerTxt') }} <span class="text-[#191919] ml-[5px]">{{ getAnswers(q) }}</span></div>
          <div class="reference-answer flex items-top">
            <div  class="flex-none w-[55px]">{{ $t('exam.analysisTxt') }}</div>
            <span class="text-[#191919]">{{ q.analysis || '--' }}</span>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>
<style lang="scss"></style>
